package 代码记录.校招笔试真题.笔试真题_2022.涂鸦多得;

/**
 * @author zx
 * @create 2022-11-03 18:03
 */
public class 滑动窗口的最大值 {
    public int[] maxSlidingWindow(int[] nums, int k) {
        //特殊情况
        if(nums.length == 0) {
            return new int[]{};
        }
        if(k == 1) {
            return  nums;
        }
        int right = 0,left = 0, count = 0, max = Integer.MIN_VALUE;
        int[] res = new int[nums.length - k + 1];
        while(right < nums.length) {
            int windowMax = nums[right];//windowMax是移入窗口的值，并记录窗口中最大值
            max = Math.max(windowMax,max);
            right++;
            while (right - left == k) {//达到窗口长度
                res[count++] = max;//该窗口最大值记录进数组
                int gun = nums[left];//gun是即将移出窗口的值
                if(gun == max){//如果移出的是最大值，将max改为剩下窗口内元素的最大值
                    int temp = Integer.MIN_VALUE;
                    for (int i = left + 1; i < right ; i++) {
                        if (nums[i] > temp) {
                            temp = nums[i];
                        }
                    }
                    max = temp;
                }
                left++;
            }
        }
        return res;
    }
}
